﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;

namespace DaInterFace
{
    public class Common
    {
        /// <summary>
        /// 数量精度
        /// </summary>
        public static int QtyPrecision = 2;
        /// <summary>
        /// 单价
        /// </summary>
        public static int PricePrecision = 2;
        /// <summary>
        /// 金额
        /// </summary>
        public static int AmountPrecision = 2;

        /// <summary>
        /// 转成数字格式
        /// </summary>
        public static Decimal Qty(String value)
        {
            Decimal rtn = 0;
            if (Decimal.TryParse(value, out rtn)) return Math.Round(rtn, QtyPrecision);
            else return 0;
        }
        /// <summary>
        /// 转成单价格式
        /// </summary>
        public static Decimal Price(String value)
        {
            Decimal rtn = 0;
            if (Decimal.TryParse(value, out rtn)) return Math.Round(rtn, PricePrecision);
            else return 0;
        }
        /// <summary>
        /// 转成金额格式
        /// </summary>
        public static Decimal Amount(String value)
        {
            Decimal rtn = 0;
            if (Decimal.TryParse(value, out rtn)) return Math.Round(rtn, AmountPrecision);
            else return 0;
        }
        /// <summary>
        /// 转成32位整形
        /// </summary>
        public static int CInt(String value)
        {
            int rtn = 0;
            if (int.TryParse(Common.CDec(value).ToString("#"), out rtn)) return rtn;
            else return 0;
        }
        /// <summary>
        /// 转成16位整形
        /// </summary>
        public static Int16 CInt16(String value)
        {
            Int16 rtn = 0;
            if (Int16.TryParse(value, out rtn)) return rtn;
            else return 0;
        }
        /// <summary>
        /// 转成小数
        /// </summary>
        public static Decimal CDec(String value)
        {
            Decimal rtn = 0;
            if (Decimal.TryParse(value, out rtn)) return Math.Round(rtn, 2);
            else return 0;
        }
        /// <summary>
        /// 转成双精度
        /// </summary>
        public static Double CDbl(String value)
        {
            Double rtn = 0;
            if (Double.TryParse(value, out rtn)) return Math.Round(rtn, 2);
            else return 0;
        }
        /// <summary>
        /// 转成布尔
        /// </summary>
        public static Boolean CBool(String value)
        {
            if (value == null)
            {
                return false;
            }
            else if (value.ToLower() == "true" || value == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 转成时间格式
        /// </summary>
        public static DateTime CTime(String value)
        {
            DateTime rtn = DateTime.MinValue;
            if (DateTime.TryParse(value, out rtn)) return rtn;
            else return DateTime.MinValue;
        }
        /// <summary>
        /// 移除小数点后几位
        /// </summary>
        /// <param name="d"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static decimal CutDecimal(decimal d, int n)
        {
            string strDecimal = d.ToString();
            int index = strDecimal.IndexOf(".");
            if (index == -1 || strDecimal.Length < index + n + 1)
            {
                strDecimal = string.Format("{0:F" + n + "}", d);
            }
            else
            {
                int length = index;
                if (n != 0)
                {
                    length = index + n + 1;
                }
                strDecimal = strDecimal.Substring(0, length);
            }
            return Decimal.Parse(strDecimal);
        }
        /// <summary>
        /// 转成汉字车号
        /// </summary>
        public static String CCarNo(String value)
        {
            if (value == null) return "";
            value = value.Replace("0", "零");
            value = value.Replace("1", "一");
            value = value.Replace("2", "二");
            value = value.Replace("3", "三");
            value = value.Replace("4", "四");
            value = value.Replace("5", "五");
            value = value.Replace("6", "六");
            value = value.Replace("7", "七");
            value = value.Replace("8", "八");
            value = value.Replace("9", "九");
            return value;
        }

        public static string Reverse(string str)
        {
            if (String.IsNullOrEmpty(str))
                return "";
            StringBuilder sb = new StringBuilder(str.Length);
            for (int i = str.Length - 1; i >= 0; i--)
            {
                sb.Append(str[i]);
            }
            return sb.ToString();
        }

        public static DateTime SystemTime()
        {
            return DateTime.Now;
        }

        public static String SystemRoot()
        {
            return System.Environment.CurrentDirectory + "\\";
        }

        public static void WriteTxt(String path, String note)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                String fileName = SystemTime().ToString("yyyyMMdd") + ".Txt";
                System.IO.FileStream fs = new System.IO.FileStream(path + fileName, System.IO.FileMode.Append);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, Encoding.Default);
                sw.WriteLine(String.Format("{0} {1}", SystemTime().ToString("HH:mm:ss"), note));
                sw.Close();
                fs.Close();
                fs = null;
                sw = null;
            }
            catch { }
        }

        public static String ReadIni(String key)
        {
            StringBuilder sb = new StringBuilder(255);
            GetPrivateProfileString("config", key, "", sb, 255, SystemRoot() + "INI\\Device");
            return sb.ToString();
        }

        public static String FilterSql(String sql)
        {
            return sql;
        }

        #region 序列化 反序列化
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception e)
            {

                return null;
            }
        }


        #endregion

        /// <summary>
        /// 获得设备指纹
        /// </summary>
        /// <returns></returns>
        public static String GetFingerprint()
        {
            String finger = "";
            try
            {
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                foreach (System.Management.ManagementObject mo in searcher.Get())
                {
                    object moItem = mo["SerialNumber"];
                    String moString = "";
                    if (moItem == null)
                    {
                        moString = GetDiskID();
                        if (moString == "")
                        {
                            moString = "7E0220010372";
                        }

                    }
                    else
                    {
                        moString = moItem.ToString().Trim();
                    }
                    byte[] result = Encoding.Default.GetBytes(moString);
                    MD5 md5 = new MD5CryptoServiceProvider();
                    byte[] output = md5.ComputeHash(result);
                    finger = Convert.ToBase64String(output);
                    break;
                }
                searcher.Dispose();
            }
            catch (Exception ex)
            {

            }
            return finger;
        }

        [DllImport("DiskID32.dll")]
        private static extern long DiskID32(ref byte DiskModel, ref byte DiskID);
        private static string GetDiskID()
        {
            byte[] DiskModel = new byte[31];
            byte[] DiskID = new byte[31];
            int i;
            string ID = "";
            if (DiskID32(ref DiskModel[0], ref DiskID[0]) != 1)
            {
                for (i = 0; i < 31; i++)
                {
                    if (Convert.ToChar(DiskID[i]) != Convert.ToChar(0))
                    {
                        ID = ID + Convert.ToChar(DiskID[i]);
                    }
                }
                ID = ID.Trim();
            }
            else
            {
                Console.WriteLine("获得设备指纹错误");
            }
            return ID;
        }

        public static string GetLocalIp()
        {
            string hostname = System.Net.Dns.GetHostName();//得到本机名
            //IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期，只得到IPv4的地址
            System.Net.IPHostEntry localhost = System.Net.Dns.GetHostEntry(hostname);
            System.Net.IPAddress localaddr = localhost.AddressList[0];
            return localaddr.ToString();
        }

        public static String EncryptString(String encryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes("X3317975");
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        public static string DecryptString(string decryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes("X3317975");
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
    }
}
